package com.ylq.reggie_take_away.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylq.reggie_take_away.common.CustomException;
import com.ylq.reggie_take_away.entity.Category;
import com.ylq.reggie_take_away.entity.Dish;
import com.ylq.reggie_take_away.entity.SetMeal;
import com.ylq.reggie_take_away.mapper.CategoryMapper;
import com.ylq.reggie_take_away.service.CategoryService;
import com.ylq.reggie_take_away.service.DishService;
import com.ylq.reggie_take_away.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    /**
     * 根据id删除分类，删除之前进行判断
     * @param ids
     */
    @Override
    public void remove(Long ids) {
        //查询当前套餐是否关联了套餐, 如果关联则抛出一个业务异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, ids);
        int count = dishService.count(dishLambdaQueryWrapper);
        if (count > 0) {
            //关联了菜品
            throw new CustomException("关联了菜品, 不能删除");
        }

        //查询当前套餐是否关联了菜品, 如果关联则抛出一个业务异常
        LambdaQueryWrapper<SetMeal> setMealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setMealLambdaQueryWrapper.eq(SetMeal::getCategoryId, ids);
        int count1 = setMealService.count(setMealLambdaQueryWrapper);
        if (count1 > 0) {
            //关联了套餐
            throw new CustomException("关联了套餐, 不能删除");
        }

        //正常删除
        super.removeById(ids);
    }
}
